import Vue from "vue";
import Router from "vue-router";
import Login from "../components/Login.vue";
import Home from "../components/Home.vue";
import Welcome from "../components/Welcome.vue";
import Users from "../components/user/Users.vue";

Vue.use(Router);

const router = new Router({
  routes: [
    { path: "/", redirect: "/login" },
    { path: "/login", component: Login },
    {
      path: "/home",
      component: Home,
      redirect: "/welcome",
      children: [
        { path: "/welcome", component: Welcome },
        {
          path: "/users",
          component: Users
        }
      ]
    }
  ]
});
router.beforeEach((to, from, next) => {
  // 只有调用next才可以方形，不然是进不去的，还可以指定跳转到其他理由。next('/login')
  //对所有的路由拦截进行判断是否登录处理

  //如果用户登录了，直接方形
  if (sessionStorage.getItem("token")) {
    next();
  } else {
    //如果用户没有登录，但是用户访问的是登录页面；next()
    if (to.path === "/login") {
      next();
    } else {
      //访问的不是登录页面，就让他跳转到登录页面
      next("/login");
    }
  }
});

export default router;
